package com.shuai.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;
import com.shuai.config.RpcConfig;
import com.shuai.constants.RpcConstant;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;

/** 配置工具类 */
public class ConfigUtils {

  /**
   * 加载配置对象
   *
   * @param tClass
   * @param prefix
   * @param <T>
   * @return
   */
  public static <T> T loadConfigProperties(Class<T> tClass, String prefix) {
    return loadConfigWithProperties(tClass, prefix, "");
  }

  /**
   * 加载配置对象，支持区分环境
   *
   * @param tClass
   * @param prefix
   * @param environment
   * @param <T>
   * @return
   */
  public static <T> T loadConfigWithProperties(Class<T> tClass, String prefix, String environment) {
    StringBuilder configFileBuilder = new StringBuilder("application");
    if (StrUtil.isNotBlank(environment)) {
      configFileBuilder.append("-").append(environment);
    }
    configFileBuilder.append(".properties");
    Props props = new Props(configFileBuilder.toString(), CharsetUtil.CHARSET_UTF_8);
    return props.toBean(tClass, prefix);
  }

  /**
   * @param tClass
   * @param prefix
   * @return
   * @param <T>
   */
  public static <T> T loadConfigYaml(Class<T> tClass, String prefix) {
    return loadConfigWithProperties(tClass, prefix, "");
  }

  public static RpcConfig loadConfigWithYaml(String configPath) {

    Yaml yaml = new Yaml();
    try (InputStream inputStream =
        ConfigUtils.class.getClassLoader().getResourceAsStream(configPath)) {
      if (inputStream == null) {
        throw new RuntimeException("配置文件不存在：" + configPath);
      }

      // 1. 解析整个YAML为Map
      Map<String, Object> rootConfig = yaml.load(inputStream);
      // 2. 提取"rpc"节点的内容
      Map<String, Object> rpcNode =
          (Map<String, Object>) rootConfig.get(RpcConstant.DEFAULT_CONFIG_PREFIX);
      if (rpcNode == null) {
        throw new RuntimeException("配置文件中缺少`rpc`节点");
      }
      // 3. 将rpc节点序列化为YAML字符串，再映射到RpcConfig
      String rpcYamlStr = yaml.dump(rpcNode);
      return yaml.loadAs(rpcYamlStr, RpcConfig.class);
    } catch (IOException e) {
      throw new RuntimeException("加载yaml配置文件失败：" + e.getMessage(), e);
    }
  }
}
